#include <iostream>
#include <string>
#include <unordered_map>
#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Buffer.h>

class DictServer
{
public:
    DictServer(uint16_t port)
        : _dictServer(&_eventLoop,
                      muduo::net::InetAddress("0.0.0.0", port),
                      "DictServer",
                      muduo::net::TcpServer::kReusePort)    //启用端口复用
    {
        _dictServer.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _dictServer.setMessageCallback(std::bind(&DictServer::onMessage,
                                                 this,
                                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _dictServer.start();
        _eventLoop.loop();
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &con)
    {
        if (con->connected())
            std::cout << "连接建立" << std::endl;
        else
            std::cout << "连接断开" << std::endl;
    }
    void onMessage(const muduo::net::TcpConnectionPtr &con, muduo::net::Buffer *buffer, muduo::Timestamp)
    {
        static std::unordered_map<std::string, std::string> dict_map{
            {"apple", "苹果"},
            {"banana", "香蕉"},
            {"orange", "橘子"}};

        std::string recv_string = buffer->retrieveAllAsString();
        std::string ret;

        auto it = dict_map.find(recv_string);
        if (it == dict_map.end())
            ret = "未知单词！！！";
        else
            ret = it->second;

        con->send(ret);
    }

private:
    //注意，TcpServer的初始化依赖于EventLoop
    //所以，_eventLoop要放在_dictServer之上
    muduo::net::EventLoop _eventLoop;   
    muduo::net::TcpServer _dictServer;
};

int main()
{
    DictServer server(8080);
    server.start();

    return 0;
}